/**
 * 项目名称: Topic_236.cpp
 * 项目路径: study/DataStructure/LeetCode/树/中等
 * 编辑时间: 2024年08月17日08时07分40秒
 * 用   户: 轻尘
 */

#include <bits/stdc++.h>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    TreeNode* ans ;
    int dfs(TreeNode* root,TreeNode* p,TreeNode* q){
        if(!root)return 0;
        int state = dfs(root->left,p,q);
        if(root == p)state |=1;
        else if(root ==q)state |=2;
        state |= dfs(root->right,p,q);
        if(state == 3 &&!ans)ans = root;
        return state;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root,p,q);
        return ans;
    }
};
